using Godot;
using System;

public partial class HurtboxComponent : Area2D
{
	[Signal] 
	public delegate void HitEventHandler();
	[Export]
	public HealthComponent healthComponent;
	PackedScene floatingTextScene = GD.Load<PackedScene>("res://scenes/ui/floating_text.tscn");

	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		AreaEntered += OnAreaEntered;
	}

	// Called every frame. 'delta' is the elapsed time since the previous frame.
	public override void _Process(double delta)
	{
	}

	public void OnAreaEntered(Area2D otherArea){
		if(otherArea is not HitboxComponent){
			return;
		}
		if(healthComponent == null){
			return ;
		}
		var hitboxComponent = otherArea as HitboxComponent;
		healthComponent.Damage(hitboxComponent.damage);

		FloatingText floatingText = floatingTextScene.Instantiate() as FloatingText;
		GetTree().GetFirstNodeInGroup("foreground_layer").AddChild(floatingText);
		floatingText.GlobalPosition = GlobalPosition + Vector2.Up *16;

		if(Math.Floor(hitboxComponent.damage) == hitboxComponent.damage ){
			floatingText.Start(hitboxComponent.damage.ToString());
		}else{
			floatingText.Start((Math.Floor(hitboxComponent.damage*10)/10).ToString());
		}

		this.EmitSignal(nameof(Hit));
	}
}
